import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/tokenStore'



const service = axios.create({
    baseURL:import.meta.env.VITE_APP_BASE_API
})
    /**
     * 请求拦截器
     * 给每个请求添加token,请求头Authorization
     */
service.interceptors.request.use((config) => {
    config.headers.Authorization = useTokenStore().TOKEN
    return config
},(e) => {
    return Promise.reject(e)
})

    /**
     *  响应拦截器
     */
service.interceptors.response.use((resp) => {
        const {code,data,message} = resp.data
        if(code === 200){
            return data
        }else if(code === 403){
            const tokenStore = useTokenStore()
            tokenStore.clear()
            ElMessage.error(message)
            setTimeout(() => {
                location.href = '/login'
            }, 1000)
        }else{
            console.log(message)
            ElMessage.error(message)
            return Promise.reject(message)
        }
    },(error) => {
        console.log(error)
        return Promise.reject(error)
    }
)

export default service